"""Data Quality API endpoints."""

from __future__ import annotations

from typing import Any

from fastapi import APIRouter, Depends, Query
from sqlalchemy.orm import Session

from ...deps import get_db, get_current_user
from ....models.user import User
from ....services.data_quality_service import DataQualityService, QualityReport

router = APIRouter(prefix="/data-quality", tags=["data-quality"])


@router.get("/summary", summary="获取数据质量概览")
def get_quality_summary(
    db: Session = Depends(get_db), current_user: User = Depends(get_current_user)
) -> dict[str, Any]:
    """
    获取数据质量快速概览.

    包括:
    - 总记录数统计
    - 关键质量指标
    """
    service = DataQualityService(db)
    return service.get_quality_summary()


@router.post("/scan", summary="执行全面数据质量扫描")
def scan_data_quality(
    auto_fix: bool = Query(False, description="是否自动修复可修复的问题"),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
) -> dict[str, Any]:
    """
    执行全面数据质量扫描.

    Args:
        auto_fix: 是否自动修复可修复的问题 (如空白姓名)

    Returns:
        完整质量报告,包含所有检测到的问题
    """
    service = DataQualityService(db)
    report: QualityReport = service.scan_all(auto_fix=auto_fix)

    return {
        "scan_time": report.scan_time.isoformat(),
        "total_records": report.total_records,
        "issues_count": report.issues_count,
        "severity_breakdown": {
            "critical": report.critical_count,
            "high": report.high_count,
            "medium": report.medium_count,
            "low": report.low_count,
        },
        "auto_fixed_count": report.auto_fixed_count,
        "issues": [
            {
                "severity": issue.severity,
                "category": issue.category,
                "entity_type": issue.entity_type,
                "entity_id": issue.entity_id,
                "field_name": issue.field_name,
                "description": issue.issue_description,
                "suggested_fix": issue.suggested_fix,
                "auto_fixable": issue.auto_fixable,
            }
            for issue in report.issues
        ],
    }
